package com.ias.system.user.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 数据库初始化器
 * 在应用启动时执行SQL脚本
 * 
 * @author IAS Team
 * @since 1.0.0
 */
@Slf4j
@Component
public class DatabaseInitializer implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) throws Exception {
        log.info("开始初始化数据库...");
        
        try {
            // 检查是否需要初始化（通过检查表是否存在）
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            
            try {
                // 尝试查询用户表，如果抛异常说明表不存在
                jdbcTemplate.queryForObject("SELECT COUNT(*) FROM sys_user", Integer.class);
                log.info("数据库表已存在，跳过初始化");
                return;
            } catch (Exception e) {
                log.info("数据库表不存在，开始执行初始化脚本");
            }
            
            // 执行初始化脚本
            executeInitScript();
            
            log.info("数据库初始化完成");
            
        } catch (Exception e) {
            log.error("数据库初始化失败", e);
            // 不抛出异常，避免影响应用启动
        }
    }
    
    private void executeInitScript() throws Exception {
        ClassPathResource resource = new ClassPathResource("sql/init.sql");
        
        if (!resource.exists()) {
            log.warn("初始化脚本不存在：sql/init.sql");
            return;
        }
        
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8))) {
            
            StringBuilder sqlBuilder = new StringBuilder();
            String line;
            
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                
                // 跳过空行和注释
                if (line.isEmpty() || line.startsWith("--")) {
                    continue;
                }
                
                sqlBuilder.append(line).append("\n");
                
                // 如果遇到分号，执行SQL
                if (line.endsWith(";")) {
                    String sql = sqlBuilder.toString().trim();
                    if (!sql.isEmpty()) {
                        try {
                            jdbcTemplate.execute(sql);
                            log.debug("执行SQL成功：{}", sql.substring(0, Math.min(50, sql.length())));
                        } catch (Exception e) {
                            log.warn("执行SQL失败：{}，错误：{}", sql.substring(0, Math.min(50, sql.length())), e.getMessage());
                        }
                    }
                    sqlBuilder.setLength(0);
                }
            }
        }
    }
} 